rule variant_filtration_snp:
    input:
        norm_vcf="{sample}.norm.vcf.gz",
        ref_fasta=config["ref_fasta"],
    output:
        snp_norm_vcf = temp("{sample}.snp.norm.vcf.gz"),
        snp_norm_vcf_tbi = temp("{sample}.snp.norm.vcf.gz.tbi"),
        snp_vcf="{sample}.snp.vcf.gz",
        snp_vcf_tbi="{sample}.snp.vcf.gz.tbi"
    shell:
        """
        gatk SelectVariants -select-type SNP -R {input.ref_fasta} -V {input.norm_vcf} -O {output.snp_norm_vcf} -OVI true 
        gatk VariantFiltration \
            -V {output.snp_norm_vcf} \
            -O {output.snp_vcf} \
            -OVI true \
            --filter-expression "vc.hasAttribute('QD') && QD < 2.0" --filter-name "QD2" \
            --filter-expression "vc.hasAttribute('QUAL') && QUAL < 30.0" --filter-name "QUAL30" \
            --filter-expression "vc.hasAttribute('SOR') && SOR > 3.0" --filter-name "SOR3" \
            --filter-expression "vc.hasAttribute('FS') && FS > 60.0" --filter-name "FS60" \
            --filter-expression "vc.hasAttribute('MQ') && MQ < 40.0" --filter-name "MQ40" \
            --filter-expression "vc.hasAttribute('MQRankSum') && MQRankSum < -12.5" --filter-name "MQRankSum-12.5" \
            --filter-expression "vc.hasAttribute('ReadPosRankSum') && ReadPosRankSum < -8.0" --filter-name "ReadPosRankSum-8"
        """


rule variant_filtration_indel:
    input:
        norm_vcf="{sample}.norm.vcf.gz",
        ref_fasta=config["ref_fasta"],
    output:
        indel_norm_vcf = temp("{sample}.indel.norm.vcf.gz"),
        indel_norm_vcf_tbi = temp("{sample}.indel.norm.vcf.gz.tbi"),
        indel_vcf="{sample}.indel.vcf.gz",
        indel_vcf_tbi="{sample}.indel.vcf.gz.tbi",
    shell:
        """
        gatk SelectVariants -select-type INDEL -R {input.ref_fasta} -V {input.norm_vcf} -O {output.indel_norm_vcf} -OVI true 
        gatk VariantFiltration \
            -V {output.indel_norm_vcf} \
            -O {output.indel_vcf} \
            --filter-expression "vc.hasAttribute('QD') && QD < 2.0" --filter-name "QD2" \
            --filter-expression "vc.hasAttribute('QUAL') && QUAL < 30.0" --filter-name "QUAL30" \
            --filter-expression "vc.hasAttribute('FS') && FS > 200.0" --filter-name "FS200" \
            --filter-expression "vc.hasAttribute('ReadPosRankSum') && ReadPosRankSum < -20.0" --filter-name "ReadPosRankSum-20" \
        """

rule merge_vcfs:
    input:
        snp_vcf="{sample}.snp.vcf.gz",
        indel_vcf="{sample}.indel.vcf.gz",
    output:
        snv_vcf="{sample}.snv.vcf.gz",
        snv_vcf_tbi="{sample}.snv.vcf.gz.tbi"
    shell:
        "gatk MergeVcfs -I {input.snp_vcf} -I {input.indel_vcf} -O {output.snv_vcf} --CREATE_INDEX true"